package com.sg.record.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.sql.ast.SQLObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sg.common.empty.core.FilterVal;
import com.sg.common.empty.service.CfgService;
import com.sg.common.login.entity.Org;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
@Component
public class ImpthApiService {
private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	CfgService service;
	
	/***
	 * 培训计划审核，计划审核后，创建培训实际信息
	 * @param checkSql
	 * @param currentMemberId
	 * @param currentTime
	 * @param depId
	 * @param ids
	 * @return
	 */
	@Transactional
	public String autoCheck(String checkSql, String currentMemberId,
			String currentTime, String ids) {
		if (StringUtils.isNotEmpty(ids)) {
			String[] split = StringUtils.split(ids, ",");
			for (String id : split) {
				String querySql = "select tr.enable,tr.createDate,tr.createMember from tr_plan tr where tr.id = ?";
				List<Map<String,Object>> planOldList = service.queryBySqlToMap(querySql,new Object[]{id}, new String[]{"enable", "createDate", "createMember"});
				Map<String, Object> planOld = planOldList.get(0);
				
				if(!StringUtils.equals((String)planOld.get("enable"), "1")){
					return "error";
				}else{
					service.excuteBySql(checkSql, new String[] { currentMemberId,
							currentTime, id });
					// 新增培训实际
					String planSql = "SELECT tr.level,tr.type,tr.enable,tr.orgCode,tr.orgDescr,"
							+ "tr.fileQNkey,tr.fileValue,tr.fileLabel,tr.relaRule,tr.ruleQNkey,tr.ruleValue,tr.ruleLabel,tr.date,tr.time,tr.place,tr.form,tr.cate,"
							+ "tr.item,tr.aim,tr.hour,tr.hour2,tr.teacher,tr.content,tr.post,tr.students,tr.needSum,tr.depId,"
							+ "tr.workShopId,tr.files FROM tr_plan tr where id =?";
					// order by id asc  limit 0,20
					List<Map<String, Object>> planObject = service.queryBySqlToMap(
							planSql, new Object[]{id}, new String[] { "level", "type", "enable",
									"orgCode", "orgDescr", "fileQNkey", "fileValue", "fileLabel","relaRule","ruleQNkey", "ruleValue", "ruleLabel", "date", "time", "place",
									"form", "cate", "item", "aim", "hour", "hour2",
									"teacher", "content", "post", "students",
									"needSum", "depId", "workShopId", "files"});
					
					String newsql = "insert into train_actual (id,level,type,orgCode,orgDescr,fileQNkey,fileValue,fileLabel,relaRule,ruleQNkey,ruleValue,ruleLabel,date,time,place,form,"
							+ "cate,item,aim,hour,hour2,teacher,content,post,students,needSum,"
							+ "depId,workShopId,createMember,createDate,plan,files,enable) values"
							+ "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'0')";
					String aid = (String) FilterVal.init("sys32Id", service).get2();
					Map<String, Object> plan = planObject.get(0);
					service.excuteBySql(
							newsql,
							new Object[] { aid, plan.get("level"),
									plan.get("type"), plan.get("orgCode"),
									plan.get("orgDescr"), plan.get("fileQNkey"),
									plan.get("fileValue"), plan.get("fileLabel"),plan.get("relaRule"),plan.get("ruleQNkey"),
									plan.get("ruleValue"), plan.get("ruleLabel"),plan.get("date"),
									plan.get("time"), plan.get("place"),
									plan.get("form"), plan.get("cate"),
									plan.get("item"), plan.get("aim"),
									plan.get("hour"),plan.get("hour2"),  plan.get("teacher"),
									plan.get("content"), plan.get("post"),
									plan.get("students"), plan.get("needSum"),
									plan.get("depId"),plan.get("workShopId"),
									currentMemberId, currentTime, id, plan.get("files")});	//, id
//					查询plan对应的课程内容，并复制到对应的培训实际中
					String pcreSql = "select poca,clst,level,hour from tr_pcre where plan=? and enable='1'";
					List<Map<String, Object>> pcreList = service.queryBySqlToMap(pcreSql, new Object[]{id}, new String[]{"poca", "clst", "level", "hour"});
					for(Map<String, Object> pcre : pcreList){
						String acreId = (String) FilterVal.init("sys32Id", service).get2();
						String acreAddSql = "insert into tr_acre (id, actual, poca, clst, level, hour, enable, createDate,createMember) values (?,?,?,?,?,?,'1',?,?)";
						service.excuteBySql(acreAddSql, new Object[]{acreId, aid, pcre.get("poca"),pcre.get("clst"),pcre.get("level"),pcre.get("hour"),currentTime,currentMemberId});
					}
					
				}
					
			}
		}
		return "success";
	}
	
	/**
	 * 培训实际完成/取消,编辑
	 * @param requestBody
	 */
	@Transactional
	public List<Map<String, Object>> updateSer(HttpServletRequest request, Map<String, Object> requestBody) {
		
		Object id = requestBody.get("id");
		Object currentTime = (String)FilterVal.init("currentTime", service).get2();
		Object currentMember = (String) FilterVal.init("currentMemberId", service).get2();
		
		Object enable = actualUpdate(requestBody, id, currentTime,
				currentMember);
		
		updateIssueList(request, requestBody, id, currentTime, currentMember);
		List<Map<String, Object>> idsMap = updateAcreList(request, requestBody, id, currentTime, currentMember);
		
//		0,未完成;1,已完成;-1,取消 ---培训实际完成或取消时,更新培训计划的状态
		if(!StringUtils.equals("0", enable.toString())){
			Object plan = requestBody.get("plan");
			String planUpSql = "update tr_plan set actualEnable =? where id =?";
			service.excuteBySql(planUpSql, new Object[]{enable,plan});
			if(StringUtils.equals("1", enable.toString())){
				ArrayList students = (ArrayList) requestBody.get("students");
				Object date = requestBody.get("date");
				Object depId = (String) FilterVal.init("depId", service).get2();
				Object workShopId = (String) FilterVal.init("workShopId", service).get2();
				for(int i=0;i<students.size();i++){
					System.out.print(students.get(i));
					String[] stu = StringUtils.split(students.get(i).toString(), "-");
					ArrayList acreList = (ArrayList)requestBody.get("acreList");
//					2019-3-27 增加-根据培训计划（实际）是否有选择标准培训课程中的课程，分别处理个人培训记录生成情况
					if(acreList.size()>0){
						for(int j=0; j< acreList.size(); j++){
							Map<String, Object> acre = (Map<String, Object>) acreList.get(j);
//							enable=1,有效;enable=0,无效
							if(StringUtils.equalsIgnoreCase(acre.get("enable").toString(), "1")){
								String nId = (String) FilterVal.init("sys32Id", service).get2();
								Object clst = acre.get("clst");		//培训课程ID
								Object hour = acre.get("hour");		//累计课时
								Object poca = acre.get("poca");		//培训岗位(性质)
								String trInsert = "insert into tr_personal (id,epnum,name,clst,actual,poca,hour,trDate,enable,createDate,createMember,workShopId,depId) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
//								生成个人培训情况记录
								service.excuteBySql(trInsert, new Object[]{nId,stu[0],stu[1],clst,id,poca,hour,date,'1',currentTime,currentMember,workShopId,depId});
							}
						}
					}else{
						String nId = (String) FilterVal.init("sys32Id", service).get2();
//						Object clst = acre.get("clst");
//						Object hour = acre.get("hour");
//						Object poca = acre.get("poca");
						Object item = requestBody.get("item");				//培训项目
						Object hour2 = requestBody.get("hour");				//培训课时
						Object post = requestBody.get("post");
						String trInsert = "insert into tr_personal (id,epnum,name,actual,item,hour2,post,trDate,enable,createDate,createMember,workShopId,depId) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
//						生成个人培训情况记录
						service.excuteBySql(trInsert, new Object[]{nId,stu[0],stu[1],id,item,hour2,post,date,'1',currentTime,currentMember,workShopId,depId});
					}
					
				}
			}
		}
		return idsMap;
	
	}

	/**
	 * 培训问题列表更新
	 * @param requestBody
	 * @param id
	 * @param currentTime
	 * @param currentMember
	 */
	public void updateIssueList(HttpServletRequest request, Map<String, Object> requestBody, Object id,
			Object currentTime, Object currentMember) {
		ArrayList issueList = (ArrayList)requestBody.get("issueList");
		for(int i=0; i< issueList.size(); i++){
//			System.out.print(issueList.get(i));
			Map<String, Object> issue = (Map<String, Object>) issueList.get(i);
			if(issue.get("id")==null){ //新增问题
				String nId= (String) FilterVal.init("sys32Id", service).get2();
				String iType = (String)issue.get("type");
				String iContent = (String)issue.get("content");
				String iEnable = (String)issue.get("enable");
				String depId = (String) FilterVal.init("depId",service).get2();
				Org myDepOrg = (Org)request.getSession().getAttribute(Constant.SESSION_MYDEPORG);
				
				String orgCode = myDepOrg.getCode();
				List<Object> orgCodeList = new ArrayList<Object>();
				orgCodeList.add(orgCode);
				Object[] depCode = orgCodeList.toArray();
				
				String orgDescr = myDepOrg.getDescr();
				List<Object> orgDescrList = new ArrayList<Object>();
				orgDescrList.add(orgDescr);
				Object[] depDescr = orgDescrList.toArray();
				
//				JSONArray codeArray = JSONArray.parseArray("[" + "\"" + orgCode + "\"" + "]");
//				JSONArray descrArray = JSONArray.parseArray("[" + "\"" + orgDescr + "\"" + "]");
				String newSql = "insert into tr_issue (id,actual,type,content,enable,depId,orgCode,orgDescr,createMember,createDate) values (?,?,?,?,?,?,?,?,?,?)";
				service.excuteBySql(newSql, new Object[]{nId, id,iType, iContent, iEnable, depId, JSONArray.toJSONString(depCode), JSONArray.toJSONString(depDescr), currentMember, currentTime});
			}else{  //更新问题
				String issueId = (String)issue.get("id");
				String iType = (String)issue.get("type");
				String iContent = (String)issue.get("content");
				String iEnable = (String)issue.get("enable");
				String iUpSql = "update tr_issue set type=?,content=?,enable=?,updateMember=?,updateDate=? where id=?";
				service.excuteBySql(iUpSql, new Object[] {iType, iContent, iEnable, currentMember, currentTime, issueId});
			}
		}
	}

	
	/**
	 * 更新培训实际
	 * @param requestBody
	 * @param id
	 * @param currentTime
	 * @param currentMember
	 * @return
	 */
	public Object actualUpdate(Map<String, Object> requestBody,
			Object id, Object currentTime, Object currentMember) {
		String upSql = "update train_actual set enable=?,students=?,needSum=?,level=?,type=?,fileQNkey=?,fileValue=?,fileLabel=?,relaRule=?,ruleQNkey=?,ruleValue=?,ruleLabel=?,orgCode=?,orgDescr=?,date=?,time=?,"
				+ "place=?,form=?,cate=?,item=?,aim=?,hour=?,hour2=?,teacher=?,content=?,post=?,summary=?,files=?,remark=?,updateMember=?,"
				+ "updateDate=? where id=?";
		Object enable = requestBody.get("enable");
		Object students = requestBody.get("students");
		students = JSONArray.toJSONString(students);
		Object needSum = requestBody.get("needSum");
		Object level = requestBody.get("level");
		Object type = requestBody.get("type");
		Object fileQNkey = requestBody.get("fileQNkey");
		fileQNkey = JSONArray.toJSONString(fileQNkey);
		Object fileValue = requestBody.get("fileValue");
		fileValue = JSONArray.toJSONString(fileValue);
		Object fileLabel = requestBody.get("fileLabel");
		fileLabel = JSONArray.toJSONString(fileLabel);
		Object relaRule = requestBody.get("relaRule");
		Object ruleQNkey = requestBody.get("ruleQNkey");
		ruleQNkey = JSONArray.toJSONString(ruleQNkey);
		Object ruleValue = requestBody.get("ruleValue");
		ruleValue = JSONArray.toJSONString(ruleValue);
		Object ruleLabel = requestBody.get("ruleLabel");
		ruleLabel = JSONArray.toJSONString(ruleLabel);
		Object orgCode = requestBody.get("orgCode");
		orgCode = JSONArray.toJSONString(orgCode);
		Object orgDescr = requestBody.get("orgDescr");
		orgDescr = JSONArray.toJSONString(orgDescr);
		Object date = requestBody.get("date");
		Object time = requestBody.get("time");
		Object place = requestBody.get("place");
		Object form = requestBody.get("form");
		form = JSONArray.toJSONString(form);
		Object cate = requestBody.get("cate");
		Object item = requestBody.get("item");
		Object aim = requestBody.get("aim");
		Object hour = requestBody.get("hour");
		Object hour2 = requestBody.get("hour2");
		Object teacher = requestBody.get("teacher");
		teacher = JSONArray.toJSONString(teacher);
		Object content = requestBody.get("content");
		Object post = requestBody.get("post");
		Object summary = requestBody.get("summary");
		Object files = requestBody.get("files");
		files = JSONArray.toJSONString(files);
		Object remark = requestBody.get("remark");
	
		service.excuteBySql(upSql, new Object[]{enable,students,needSum,level,type,fileQNkey,fileValue,fileLabel,relaRule,ruleQNkey,ruleValue,ruleLabel,orgCode,orgDescr,date,time,place,form,cate,item,
				aim,hour,hour2,teacher,content,post,summary,files,remark,currentMember,currentTime,id});
		return enable;
	}
	
	/**
	 * 培训计划plan关联的培训课程新增/更新
	 * @param request
	 * @param requestBody
	 * @param id
	 * @param currentTime
	 * @param currentMember
	 */
	public List<Map<String, Object>> updatePcreList(HttpServletRequest request, Map<String, Object> requestBody, Object id) {
		List<Map<String, Object>> idsMap = new ArrayList<Map<String, Object>>();
		String enable = (String)requestBody.get("enable");
		String content = (String)requestBody.get("content");
		String remark = (String)requestBody.get("remark");
		String pcreUpSql = "update record_impth set enable=?,content=?,remark=? where id=?";
		service.excuteBySql(pcreUpSql, new Object[] {enable, content, remark,  id});
		
//		ArrayList pcreList = (ArrayList)requestBody.get("pcreList");
//		System.out.print(pcreList);
//		for(int i=0; i< pcreList.size(); i++){
////			System.out.print(pcreList.get(i));
//			Map<String, Object> pcre = (Map<String, Object>) pcreList.get(i);
//			if(pcre.get("id")==null){ //新增问题
//				Map<String, Object> idMap = new HashMap<String, Object>();
//				String nId= (String) FilterVal.init("sys32Id", service).get2();
//				String clst = (String)pcre.get("clst");
//				String level = (String)pcre.get("level");
//				String hour = String.valueOf(pcre.get("hour"));
//				String poca = (String)pcre.get("poca");
//				String enable = (String)pcre.get("enable");
//				String newSql = "insert into tr_pcre (id,poca,plan,clst,hour,level,enable,createMember,createDate) values (?,?,?,?,?,?,?,?,?)";
//				service.excuteBySql(newSql, new Object[]{nId, poca, id, clst, hour, level, enable});
//				idMap.put("id", nId);
//				idsMap.add(idMap);
//			}else{  //更新问题
//				String pcreId = (String)pcre.get("id");
//				String poca = (String)pcre.get("poca");
//				String clst = (String)pcre.get("clst");
//				String hour = String.valueOf(pcre.get("hour"));
//				String enable = (String)pcre.get("enable");
//				String pcreUpSql = "update tr_pcre set poca=?,clst=?,hour=?,enable=?,updateMember=?,updateDate=? where id=?";
//				service.excuteBySql(pcreUpSql, new Object[] {poca, clst, hour, enable,  pcreId});
//			}
//		}
		return idsMap;
	}
	
	/**
	 * 培训实际actual关联的培训课程新增/更新
	 * @param request
	 * @param requestBody
	 * @param id
	 * @param currentTime
	 * @param currentMember
	 */
	public List<Map<String, Object>> updateAcreList(HttpServletRequest request, Map<String, Object> requestBody, Object id,
			Object currentTime, Object currentMember) {
		List<Map<String, Object>> idsMap = new ArrayList<Map<String, Object>>();
		ArrayList acreList = (ArrayList)requestBody.get("acreList");
		for(int i=0; i< acreList.size(); i++){
			Map<String, Object> acre = (Map<String, Object>) acreList.get(i);
			if(acre.get("id")==null){ //新增问题
				Map<String, Object> idMap = new HashMap<String, Object>();
				String nId= (String) FilterVal.init("sys32Id", service).get2();
				String clst = (String)acre.get("clst");
				String level = (String)acre.get("level");
				String hour = String.valueOf(acre.get("hour"));
				String poca = (String)acre.get("poca");
				String enable = (String)acre.get("enable");
				
				String newSql = "insert into tr_acre (id,poca,actual,clst,hour,level,enable,createMember,createDate) values (?,?,?,?,?,?,?,?,?)";
				service.excuteBySql(newSql, new Object[]{nId, poca, id, clst, hour, level, enable, currentMember, currentTime});
				idMap.put("id", nId);
				idsMap.add(idMap);
			}else{  //更新问题
				String pcreId = (String)acre.get("id");
				String poca = (String)acre.get("poca");
				String clst = (String)acre.get("clst");
				String hour = String.valueOf(acre.get("hour"));
				String enable = (String)acre.get("enable");
				String acreUpSql = "update tr_acre set poca=?,clst=?,hour=?,enable=?,updateMember=?,updateDate=? where id=?";
				service.excuteBySql(acreUpSql, new Object[] {poca, clst, hour, enable, currentMember, currentTime, pcreId});
			}
		}
		return idsMap;
	}
}
